import json

from django.http import JsonResponse
from meiduo_move_server.utils import request_utils
from meiduo_move_server.utils import img_utils
from meiduo_move_server.utils.mysql_utils import MySQLUtils
from meiduo_move_server import project_constants as p_const
from meiduo_move_server.utils import data_type_change_utils
from user.utils import jwt_utils


def addUserCartInfo(req):
    """
    向用户购物车信息表中添加信息
    """
    body = request_utils.getPostDataToDict(req.body)
    token = body.get('token')
    token_data = jwt_utils.get_payload(token)
    if token_data is None:
        return JsonResponse({
            'mark': p_const.MARK_ERROR,
            'message': '您还未登录，请先登录账号'
        })
    userAccount = token_data.get('userAccount')  # 获取用户账号
    userId = token_data.get('userId')  # 获取用户id
    goodsId = body.get('goodsId')  # 获取商品Id
    selectParam = body.get('selectParam')  # 获取用户选择的商品参数
    selectParam = json.dumps(selectParam)
    goodsNumber = body.get('selectNumber')  # 用户加入购物车该商品的数量
    # 查询该购物车信息是否已经存在
    sql = """
    SELECT id
    FROM user_cart_info
    WHERE select_param = %s
      AND user_account_info_id = %s
      AND goods_info_id = %s;
    """
    res_data = MySQLUtils.select(sql, (selectParam, userId, goodsId))
    print(res_data)
    if res_data.get('row_count') >= 1:  # 数据库中已经存在该购物车信息
        userCartInfoId = res_data.get('data')[0][0]
        sql = """
        UPDATE user_cart_info
        SET pay_goods_number = (pay_goods_number + %s)
        WHERE id = %s;
        """
        res_count = MySQLUtils.update(sql, (goodsNumber, userCartInfoId))
        if res_count < 1:
            return JsonResponse({
                'mark': p_const.MARK_ERROR,
                'message': '添加购物车失败'
            })
    # print(res_data)
    else:  # 数据库中不存在该购物车信息
        sql = """
        CALL p_insert_user_cart_info(%s, %s, %s, %s);
        """
        row_count = MySQLUtils.update(sql, (userAccount, goodsId, selectParam, goodsNumber))
        if row_count < 1:
            return JsonResponse({
                'mark': p_const.MARK_ERROR,
                'message': '添加购物车失败'
            })
    return JsonResponse({
        'mark': p_const.MARK_SUCCESS,
        'message': '添加购物车成功'
    })


def getUserCartInfo(req):
    """
    获取用户的购物车信息
    """
    token = jwt_utils.get_payload(req.GET.get('token'))
    userId = token.get('userId')
    sql = """
    SELECT id, goods_info_id, select_param, pay_goods_number, selected FROM user_cart_info WHERE user_account_info_id = %s ORDER BY id DESC;
    """
    res_data = MySQLUtils.select(sql, (userId,))
    if res_data.get('row_count') < 1:
        return JsonResponse({
            'mark': p_const.MARK_ERROR,
            'message': '暂无用户购物车商品信息'
        })
    userCartInfo = data_type_change_utils.tuple2dict(['id', 'goodsId', 'selectParams', 'goodsNumber', 'selected'], res_data['data'])
    # 将Json字符串转为字典
    for i in userCartInfo:
        i['selectParams'] = json.loads(i['selectParams'])
        goodsId = i['goodsId']
        sql = """
        SELECT goods_picture_path
        FROM goods_picture_info
        WHERE goods_info_id = %s
        LIMIT 1;
        """
        res_data = MySQLUtils.select(sql, (goodsId, ))
        i['goodsPicturePath'] = res_data['data'][0][0]
        sql = """
        SELECT goods_name, goods_price, goods_freight
        FROM goods_info
        WHERE id = %s;
        """
        res_data = MySQLUtils.select(sql, (goodsId,))
        i['goodsName'] = res_data['data'][0][0]
        i['goodsPrice'] = res_data['data'][0][1]
        i['goodsFreight'] = res_data['data'][0][2]
        # print(res_data)
    # print(userCartInfo)
    # print(res_data['data'])
    return JsonResponse({
        'mark': p_const.MARK_SUCCESS,
        'message': '获取用户购物车商品信息成功',
        'data': userCartInfo
    })


def updateUserCartGoodsNumber(req):
    """
    修改用户购物车商品的数量
    """
    body = request_utils.getPostDataToDict(req.body)
    userCartInfoId = body.get('userCartInfoId')
    goodsNumber = body.get('goodsNumber')
    # print(userCartInfoId, goodsNumber)
    sql = """
    UPDATE user_cart_info
    SET pay_goods_number = %s
    WHERE id = %s;
    """
    row_count = MySQLUtils.update(sql, (goodsNumber, userCartInfoId))
    # print(row_count)
    if row_count < 1:
        return JsonResponse({
            'mark': p_const.MARK_ERROR,
            'message': '商品信息更新失败'
        })
    return JsonResponse({
        'mark': p_const.MARK_SUCCESS,
        'message': '商品信息更新成功'
    })


def deleteUserCartInfo(req):
    """
    删除用户购物车商品信息
    """
    body = request_utils.getPostDataToDict(req.body)
    userCartInfoIdArr = body.get('userCartInfoIdArr')
    # userCartInfoId = ', '.join(userCartInfoIdArr)
    # userCartInfoId = '(' + userCartInfoId + ')'
    # print(userCartInfoId)
    for userCartInfoId in userCartInfoIdArr:
        sql = """
        DELETE FROM user_cart_info
        WHERE id = %s;
        """
        row_count = MySQLUtils.update(sql, (userCartInfoId))
        if row_count < 1:
            return JsonResponse({
                'mark': p_const.MARK_ERROR,
                'message': '购物车商品信息删除失败'
            })
    return JsonResponse({
        'mark': p_const.MARK_SUCCESS,
        'message': '购物车商品信息删除成功'
    })


def getCartGoodsInfoByIdArr(req):
    """
    通过购物车商品id获取商品信息
    """
    body = request_utils.getPostDataToDict(req.body)
    goodsIds = body.get('goodsIds')
    goodsIds = goodsIds.split(',')
    # print(goodsIds)
    goodsInfoArr = []
    for goodsId in goodsIds:
        # print(goodsId)
        sql = """
        SELECT uci.id,
               uci.select_param,
               uci.pay_goods_number,
               uci.goods_info_id,
               gi.goods_name,
               gi.goods_price,
               gi.goods_freight
        FROM user_cart_info uci,
             goods_info gi
        WHERE uci.goods_info_id = gi.id
          AND uci.id = %s;
        """
        res_data = MySQLUtils.select(sql, (goodsId,))
        if res_data.get('row_count') < 1:
            return JsonResponse({
                'mark': p_const.MARK_ERROR,
                'message': '获取商品信息失败'
            })
        goodsInfo = data_type_change_utils.tuple2dict(
            ['id', 'goodsParam', 'goodsNumber', 'goodsInfoId', 'goodsName', 'goodsPrice', 'goodsFreight'],
            res_data.get('data')
        )[0]
        goodsInfo['goodsParam'] = json.loads(goodsInfo['goodsParam'])
        sql = """
        SELECT goods_picture_path
        FROM goods_picture_info
        WHERE goods_info_id = %s
        LIMIT 1;
        """
        res_data = MySQLUtils.select(sql, (goodsInfo.get('goodsInfoId'),))
        if res_data.get('row_count') < 1:
            return JsonResponse({
                'mark': p_const.MARK_ERROR,
                'message': '获取商品信息失败'
            })
        goodsInfo['goodsPicturePath'] = res_data.get('data')[0][0]
        goodsInfoArr.append(goodsInfo)
    # print(goodsInfoArr)
    return JsonResponse({
        'mark': p_const.MARK_SUCCESS,
        'message': '获取商品信息成功',
        'data': goodsInfoArr
    })


def getBestNewCartInfoId(req):
    """
    获取最新的购物车信息id
    """
    token = jwt_utils.get_payload(request_utils.getPostDataToDict(req.body).get('token'))
    userId = token.get('userId')
    sql = """
        SELECT id FROM user_cart_info WHERE user_account_info_id = %s ORDER BY id DESC LIMIT 1;
        """
    res_data = MySQLUtils.select(sql, (userId,))
    bestNewCartInfoId = res_data.get('data')[0][0]
    return JsonResponse({
        'mark': p_const.MARK_SUCCESS,
        'message': '获取最新购物车商品信息编号成功',
        'data': bestNewCartInfoId
    })
